package com.crr.controller;

import com.crr.bean.Dept;
import com.crr.common.bean.ResultBean;
import com.crr.common.controller.BaseController;
import com.crr.common.group.IUpdate;
import com.crr.query.DeptQuery;
import com.crr.service.DeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@Api(tags = "部门管理")
@RestController
@RequestMapping("/v1")
public class DeptController extends BaseController {
    @Autowired
    DeptService deptService;

    @ApiOperation("新增部门")
    @PostMapping("/dept")
    public ResultBean save(@Validated @RequestBody Dept dept, BindingResult result) {
        validate(result);
        int res = deptService.save(dept);
        return saveResult(res);
    }

    @ApiOperation("删除部门")
    @DeleteMapping("/dept")
    public ResultBean delete(int id) {
        int res = deptService.delete(id);
        if (res == 2) {
            return fail("请先删除子部门");
        }
        return deleteResult(res);
    }

    @ApiOperation("修改部门")
    @PutMapping("/dept")
    public ResultBean update(@Validated({IUpdate.class}) @RequestBody Dept dept, BindingResult result) {
        validate(result);
        int res = deptService.update(dept);
        return updateResult(res);
    }

    @ApiOperation("修改状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "部门id", dataTypeClass = Integer.class, required = true, paramType = "query"),
            @ApiImplicitParam(name = "status", value = "部门状态", dataTypeClass = Integer.class, required = true, paramType = "query")
    })
    @PutMapping("/dept/status")
    public ResultBean updateStatus(@RequestParam(value = "id", required = true) int id,
                                   @RequestParam(value = "status", required = true) int status) {
        int res = deptService.updateStatus(id, status);
        return updateResult(res);
    }
    @ApiOperation("查询部门")
    @PostMapping("/dept/query")
    public ResultBean<DeptQuery> query(@RequestBody DeptQuery deptQuery) {
        List list=deptService.queryChildDept(deptQuery);
        return success("部门列表",list);
    }
    @ApiOperation("查询部门树")
    @GetMapping("/dept/queryTree")
    public ResultBean queryTree(){
       List<Map> res= deptService.queryTree();
       return success("部门树",res);
    }
}
